package com.demo.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
public class NettyServer implements CommandLineRunner {

    private final ServerBootstrap serverBootstrap;
    private final InetSocketAddress tcpPort;

    @Autowired
    public NettyServer(
            @Qualifier("serverBootstrap") ServerBootstrap serverBootstrap,
            InetSocketAddress tcpPort) {
        this.serverBootstrap = serverBootstrap;
        this.tcpPort = tcpPort;
    }

    @Override
    public void run(String... args) throws Exception {
        ChannelFuture future = serverBootstrap.bind(tcpPort).sync();
        System.out.println("Netty server started at port: " + tcpPort.getPort());
        future.channel().closeFuture().sync();
    }
}

